package com.solution.wx.core.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.solution.common.constants.PublicStatus;
import com.solution.common.utils.upload.OssUploadFile;
import com.solution.wx.core.util.WechatUtil;

/**
 * 微信端图片上传控制层
 * 
 * @author: solin
 * @date: 2017年11月22日 下午5:33:32
 */
@RequestMapping("/wx/upload")
@Controller("wxUploadController")
public class UploadController {
	private static final Logger logger = LoggerFactory.getLogger(UploadController.class);

	/**
	 * 将微信上传的图片保存到阿里云
	 * @param request
	 * @return
	 * @author: solin
	 * @date: 2017年11月23日 上午9:04:10
	 */
	@SuppressWarnings("resource")
	@RequestMapping("/picture")
	@ResponseBody
	public JSONObject savePicture(HttpServletRequest request) {
		JSONObject result = new JSONObject();
		String mediaId = request.getParameter("mediaId");
		
		FileOutputStream fileOut = null;
		File file = null;
		InputStream is =  null;
		try {
			//请求下载媒体文件地址
			String url = WechatUtil.DOWNLOAD_MEDIA_URL.replace("ACCESS_TOKEN", WechatUtil.getAccessToken()).replace("MEDIA_ID", mediaId);
			
			URL urlGet = new URL(url);
			HttpURLConnection conn = (HttpURLConnection) urlGet.openConnection();
			conn.setRequestMethod("GET"); // 必须是get方式请求
			conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
			conn.setDoOutput(true); 
			conn.setDoInput(true);
			conn.connect(); 
			// 获取文件转化为byte流
			is = conn.getInputStream();
			String ontentType = conn.getHeaderField("Content-Type");
			// 根据内容类型获取扩展名
			String fileExt = getFileexpandedName(ontentType);
			// 将mediaId作为文件名
			String fileName = String.valueOf(UUID.randomUUID()).replace("-", "") + fileExt;
			//上传到阿里云
			String filePath = OssUploadFile.uploadFileToAliyun(is, fileName, conn.getContentLength());
			
			//保存到本地
			//***************************************************************************
			/*String realPath = Thread.currentThread().getContextClassLoader().getResource("/").getPath().split("WEB-INF")[0].replace("%20", " "); 
			String realFilePath = realPath + "/upload/";
			file = new File(realFilePath+fileName);
			// 写入到文件
			fileOut = new FileOutputStream(file);
			is = conn.getInputStream();
			if (fileOut != null) {
				int c = is.read();
				while (c != -1) {
					fileOut.write(c);
					c = is.read();
				}
			}*/
			//***************************************************************************
			
			//断开连接
			conn.disconnect();
			
			result.put("filePath", filePath);
			result.put(PublicStatus.RESULT_CODE, "1");
			result.put(PublicStatus.RESULT_MSG, "上传文件成功");
			
		} catch (Exception e) {
			/*
			 * 必须关闭文件流 否则JDK运行时，文件被占用其他进程无法访问
			 */
			result.put(PublicStatus.RESULT_CODE, "-1");
			result.put(PublicStatus.RESULT_MSG, "上传文件失败");
			logger.error("上传文件异常==>", e);
		} finally {
			try {
				is.close();
				//fileOut.close();
			} catch (IOException e2) {
				logger.error("{}", e2);
			}
		}
		return result;
	}
	
	/**
	 * 根据内容类型判断文件扩展名
	 * @param contentType 内容类型
	 * @return
	 */
	public String getFileexpandedName(String contentType) {
		String fileEndWitsh = "";
		if ("image/jpeg".equals(contentType))
			fileEndWitsh = ".jpg";
		else if ("audio/mpeg".equals(contentType))
			fileEndWitsh = ".mp3";
		else if ("audio/amr".equals(contentType))
			fileEndWitsh = ".amr";
		else if ("video/mp4".equals(contentType))
			fileEndWitsh = ".mp4";
		else if ("video/mpeg4".equals(contentType))
			fileEndWitsh = ".mp4";
		return fileEndWitsh;
	}

}
